package com.example.service.impl;

import com.example.entity.EmpExpr;
import com.example.entity.EmpLog;
import com.example.entity.Employee;
import com.example.entity.LoginInfo;
import com.example.mapper.EmpExprMapper;
import com.example.mapper.EmployeeMapper;
import com.example.query.EmpQueryParam;
import com.example.service.EmpLogService;
import com.example.service.EmployeeService;

import com.example.util.JwtUtil;
import com.example.util.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private EmpExprMapper empExprMapper;

    @Autowired
    private EmpLogService empLogService;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public List<Employee> findAll() {
        return employeeMapper.findAll();
    }

//    @Override
//    public PageResult page(Integer page, Integer pageSize, String name , Integer gender, LocalDate begin, LocalDate end) {
//        // 1. 设置分页参数
//        PageHelper.startPage(page, pageSize);
//
//        // 2. 调用Mapper层方法
//        List<Employee> empList = employeeMapper.list(name, gender, begin, end);
//        // 构建分页对象
//        PageInfo<Employee> pageInfo = new PageInfo<>(empList);
//
//        // 3. 把 PageHelper 的数据封装到我们的 PageResult 中
//        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
//    }

    @Override
    public PageResult page(EmpQueryParam empQueryParam) {
        // 1. 设置分页参数
        PageHelper.startPage(empQueryParam.getPage(), empQueryParam.getPageSize());

        // 2. 调用Mapper层方法
        List<Employee> empList = employeeMapper.list(empQueryParam);
        // 构建分页对象
        PageInfo<Employee> pageInfo = new PageInfo<>(empList);

        // 3. 把 PageHelper 的数据封装到我们的 PageResult 中
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(Employee employee) {
        try {
            // 1.保存到员工表的信息，此时员工表新增一条记录
            employee.setCreateTime(LocalDateTime.now());
            employee.setUpdateTime(LocalDateTime.now());
            employeeMapper.insert(employee);
            int i = 1 / 0;

            // 2. 保存该员工的工作经历到工作经历表中
            // 这一步需要拿到新增员工记录的员工id，然后保存到工作经历表
            // 这个id已经保存到了employee对象中
            // 因为mybatis提供了主键返回功能：@Options(useGeneratedKeys = true, keyProperty = "id")
            Integer employeeId = employee.getId();
            List<EmpExpr> empExprList = employee.getEmpExprList();
            if (!CollectionUtils.isEmpty(empExprList)) {
                empExprList.forEach(empExpr -> {
                    empExpr.setEmpId(employeeId);
                    empExpr.setCreateTime(LocalDateTime.now());
                    empExpr.setUpdateTime(LocalDateTime.now());
                    empExpr.setCreateBy("System");
                    empExpr.setUpdateBy("System");
                    System.out.println(empExpr);
                });
                empExprMapper.insertBatch(empExprList);
            }
        } finally {
            // 记录操作日志
            EmpLog empLog = new EmpLog(null, LocalDateTime.now(), employee.toString());
            empLogService.insertLog(empLog);
        }

    }

    @Transactional
    @Override
    public void deleteByIds(List<Integer> ids) {
        // 1. 删除员工基本信息（员工表）
        employeeMapper.deleteByIds(ids);

        // 2. 删除员工工作经历信息（工作经历表）
        empExprMapper.deleteByEmpIds(ids);
    }

    @Override
    public Employee getById(Integer id) {
        return employeeMapper.selectById(id);
    }

    @Transactional
    @Override
    public void update(Employee employee) {
        // 1. 根据id更新员工基本信息
        employee.setUpdateTime(LocalDateTime.now());
        employeeMapper.updateById(employee);

        // 2. 更新关联的工作经历表，先删除旧的
        empExprMapper.deleteByEmpIds(Arrays.asList(employee.getId()));

        // 3. 新增新的
        Integer employeeId = employee.getId();
        List<EmpExpr> empExprList = employee.getEmpExprList();
        if (!CollectionUtils.isEmpty(empExprList)) {
            empExprList.forEach(empExpr -> {
                empExpr.setUpdateTime(LocalDateTime.now());
                empExpr.setEmpId(employeeId);
            });
            empExprMapper.insertBatch(empExprList);
        }
    }

    //
//    @Override
//    public LoginInfo login(Employee employee) {
//        Employee employeeLogin = employeeMapper.selectUsernameAndPassword(employee);
//        if (employeeLogin != null) {
//            LoginInfo loginInfo = new LoginInfo(employeeLogin.getId(), employeeLogin.getUserName(), employeeLogin.getName(), null);
//            return loginInfo;
//        }
//        return null;
//    }
    @Override
    public LoginInfo login(Employee employee) {
        Employee employeeLogin = employeeMapper.selectUsernameAndPassword(employee);
        if (employeeLogin != null) {
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", employeeLogin.getId());
            claims.put("username", employeeLogin.getUserName());
            String token = jwtUtil.generateToken(claims);
            LoginInfo loginInfo = new LoginInfo(employeeLogin.getId(), employeeLogin.getUserName(), employeeLogin.getName(), token);
            return loginInfo;
        }
        return null;
    }

}